package com.wisdom.web.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wisdom.exceptions.RoleNotFoundException;
import com.wisdom.model.dao.RoleDao;
import com.wisdom.model.entities.Role;

@Controller
@RequestMapping(value = "/admin/roles")
public class RoleController {
	public static final String LIST_ROLES = "roles/list_roles",
			ROLE_HAS_BEEN_ADDED = "redirect:/admin/roles/all",
			ROLE_HAS_BEEN_REMOVED = "redirect:/admin/roles/all",
			ROLE_HAS_BEEN_MODIFIED = "redirect:/admin/roles/all",
			ADD_ROLE_FORM = "roles/add_role",
			ERROR = "roles/list_roles";
	@Autowired
	private RoleDao roleDao;

	@RequestMapping(value = "/all")
	public String getRoles(Model model) {
		model.addAttribute("roles", roleDao.getRoles());
		return LIST_ROLES;
	}

	@RequestMapping(value = "/add_role")
	public String addRole(@RequestParam(required=false) String roleName, Model model) {
		if (roleName == null)
			return ADD_ROLE_FORM; 
		Role role = new Role();
		role.setRole(roleName);
		roleDao.add(role);

		model.addAttribute("role", role);

		return ROLE_HAS_BEEN_ADDED;
	}

	@RequestMapping(value = "/remove/{roleName}")
	public String removeRole(@PathVariable String roleName, Model model) {
		Role role;
		try {
			role = roleDao.remove(roleName);
		} catch (RoleNotFoundException ex) {
			return ERROR;
		}
		model.addAttribute("role", role);
		return ROLE_HAS_BEEN_REMOVED;
	}
	@RequestMapping(value = "/modify/{roleOldName}")
	public String modifyRole(@PathVariable String roleOldName, @RequestParam(required=false) String roleName, Model model) {
		if (roleName == null || roleOldName == null)
			return "roles/modify_role";
		Role role;
		try {
			role = roleDao.getRole(roleOldName);
			role.setRole(roleName);
			roleDao.update(role);
		} catch (RoleNotFoundException e) {
			return ERROR;
		}
		return ROLE_HAS_BEEN_MODIFIED;				
	}
}
